package com.liu.juc.sync;

/**
 * @author LIU
 * @version 1.0
 * @date 2024/2/20 9:51
 * @description TODO
 * synchronized 是 java关键字，不需要手动释放锁
 */
public class SaleTicket {

    public static void main(String[] args) {
        // 创建多个线程，调用资源类
        new Thread(new MyTask(), "AA").start();

        new Thread(new MyTask(), "BB").start();

        new Thread(new MyTask(), "CC").start();
    }
}

class MyTask implements Runnable {
    // ticket 对象 共享资源
    static Ticket ticket = new Ticket();

    @Override
    public void run() {
        for (int i = 0; i < 40; i++) {
            ticket.sale();
        }
    }
}

// 资源类
class Ticket {
    private int number = 30;

    // 卖票
    public synchronized void sale() {
        // 判断是否有票
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + " ：卖出：" + number--);

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
